<!-- 设备编辑弹窗 -->
<template>
  <div class="ele-body">
    <a-card :title="deviceModalApp.title" :bordered="false">
      <a-form
        ref="form2"
        :model="deviceModalApp.device"
        :rules="deviceModalApp.rules"
        :label-col="{md: {span: 7}, sm: {span: 24}}"
        :wrapper-col="{md: {span: 17}, sm: {span: 24}}">
        <a-row :gutter="16">
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="设备名称:" name="name">
              <a-input
                v-model:value="deviceModalApp.device.name"
                placeholder="请输入设备名称"
                :maxlength="255"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="设备型号:" name="model">
              <a-input
                v-model:value="deviceModalApp.device.model"
                placeholder="请输入设备型号"
                :maxlength="255"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="设备类型:" name="type">
              <m-dict-select
                v-model:value="deviceModalApp.device.type"
                placeholder="请选择设备类型"
                dict="设备类型"/>
            </a-form-item>
          </a-col>

          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="购入日期:" name="purchaseDate">
              <a-date-picker
                v-model:value="deviceModalApp.device.purchaseDate"
                placeholder="请选择购入日期"
                value-format="YYYY-MM-DD H:m:s"
                class="ele-fluid"/>
            </a-form-item>
          </a-col>

          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="使用日期:" name="useDate">
              <a-date-picker
                v-model:value="deviceModalApp.device.useDate"
                placeholder="请选择使用日期"
                value-format="YYYY-MM-DD H:m:s"
                class="ele-fluid"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="制造单位:" name="manufacturer">
              <m-dict-select
                v-model:value="deviceModalApp.device.manufacturer"
                placeholder="请选择制造单位"
                dict="制造单位"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="使用单位:" name="useOrganization">
              <m-dict-select
                v-model:value="deviceModalApp.device.useOrganization"
                placeholder="请选择使用单位"
                dict="使用单位"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="设备位置:" name="location">
              <a-input
                v-model:value="deviceModalApp.device.location"
                placeholder="请输入设备位置"
                :maxlength="255"
                allow-clear
              />
            </a-form-item>
          </a-col>

          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="设备区域:" name="area">
              <m-dict-select
                v-model:value="deviceModalApp.device.area"
                placeholder="请选择设备区域"
                dict="设备区域"/>
            </a-form-item>
          </a-col>

          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="设备图片:" name="img">
<!--              <a-input-->
<!--                v-model:value="deviceModalApp.device.img"-->
<!--                placeholder="请输入设备图片"-->
<!--                :maxlength="255"-->
<!--                allow-clear-->
<!--              />-->
              <image-upload
                :associate-form-id="deviceModalApp.device.eid"
                associate-form-name="device" ref="imageRef" ></image-upload>
            </a-form-item>
          </a-col>

<!--          <a-col :lg="6" :md="12" :sm="24" :xs="24">-->
<!--            <a-form-item label="二维码:" name="qrCode">-->
<!--              <a-input-->
<!--                v-model:value="deviceModalApp.device.qrCode"-->
<!--                placeholder="请输入二维码"-->
<!--                :maxlength="255"-->
<!--                allow-clear-->
<!--              />-->
<!--            </a-form-item>-->
<!--          </a-col>-->

          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item :wrapper-col="{md: {offset: 6}}" style="margin-bottom: -20px">
              <!--class="ele-pull-right"-->
              <div v-if="deviceModalApp.display">
                <teleport to="#deviceEditModalFooter">
                  <div>
                    <a-space size="middle">
                      <a-button @click="deviceListApp.editModalShowing=false">取消
                      </a-button>
                      <a-button
                        type="primary"
                        @click="onSubmit(deviceModalApp.device)"
                        :loading="loading">提交
                      </a-button>
                      <!--<a-button v-if="!eid"
                                type="dashed"
                                @click="continueSubmit"
                                :loading="loading">继续提交
                      </a-button>-->
                    </a-space>
                  </div>
                </teleport>
              </div>
              <div v-if="!deviceModalApp.display">
                <a-space size="middle">
                  <a-button @click="onBack()">返回列表</a-button>
                  <a-button
                    type="primary"
                    @click="onSubmit(deviceModalApp.device)"
                    :loading="loading">提交
                  </a-button>
                  <!--<a-button v-if="!eid"
                            type="dashed"
                            @click="continueSubmit"
                            :loading="loading">继续提交
                  </a-button>-->
                </a-space>
              </div>

            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

  </div>

</template>

<script>
import {defineComponent, inject, reactive, onMounted, ref} from 'vue'
import {useRoute, useRouter} from "vue-router"
import {DeviceService} from "@/views/repair/repairManagement/device/deviceService";
import {VXETable} from 'vxe-table'
import {useStore} from "vuex";
import regions from 'ele-admin-pro/packages/regions.js';
import attachmentService from "@/components/MFileUpload/attachmentService";

import MDictSelect from "@/components/MDict/dictSelect";
import ImageUpload from "@/components/MImageUpload/ImageUpload";

export default defineComponent({
  components: {
    ImageUpload,
    MDictSelect,
  },
  setup() {
    // 省市区数据
    const cityData = regions
    const route = useRoute();
    const router = useRouter();
    const store = useStore();
    const imageRef=ref(null);
    let routeId = route.params.id;
    let deviceListApp = inject('deviceListApp', reactive({}));
    let deviceGrid = inject('deviceGrid', reactive({}))
    const deviceModalApp = reactive({
      id: null,
      device: {},
      isEdit: false,
      display: false
    });
    deviceModalApp.rules = {
      name: [
        {
          required: true,
          type: 'string',
          message: '请输入设备编号',
          trigger: 'blur'
        }
      ],
      model: [
        {
          required: true,
          type: 'string',
          message: '请输入设备型号',
          trigger: 'blur'
        }
      ],
      type: [
        {
          required: true,
          type: 'string',
          message: '请输入设备类型',
          trigger: 'blur'
        }
      ],
      purchaseDate: [
        {
          required: false,
          type: 'string',
          message: '请输入购入日期',
          trigger: 'blur'
        }
      ],
      useDate: [
        {
          required: false,
          type: 'string',
          message: '请输入使用日期',
          trigger: 'blur'
        }
      ],
      manufacturer: [
        {
          required: false,
          type: 'string',
          message: '请输入制造单位',
          trigger: 'blur'
        }
      ],
      useOrganization: [
        {
          required: false,
          type: 'string',
          message: '请输入使用单位',
          trigger: 'blur'
        }
      ],
      location: [
        {
          required: true,
          type: 'string',
          message: '请输入设备位置',
          trigger: 'blur'
        }
      ],
      area: [
        {
          required: false,
          type: 'string',
          message: '请输入设备区域',
          trigger: 'blur'
        }
      ],
      img: [
        {
          required: false,
          type: 'string',
          message: '请输入设备图片',
          trigger: 'blur'
        }
      ],
      qrCode: [
        {
          required: false,
          type: 'string',
          message: '请输入二维码',
          trigger: 'blur'
        }
      ],
    }

    onMounted(() => {
      //清理数据
      deviceModalApp.device = reactive({});
      if (routeId) {//路由
        deviceModalApp.id = routeId;
        deviceModalApp.display = false;
        findDevice(deviceModalApp.id);
      } else if (deviceListApp.editModalForEdit) {//修改弹窗
        deviceModalApp.id = deviceListApp.currentId;
        deviceModalApp.display = true;
      } else if (!deviceListApp.editModalForEdit && deviceListApp.addModalForEdit) {//新增弹窗
        deviceModalApp.display = true;
      } else {
        deviceModalApp.title = "新增学生";
      }
      if (deviceModalApp.id) findDevice(deviceModalApp.id);
    })

    const findDevice = (id) => {
      DeviceService.findDeviceForView(id).then((res) => {
        deviceModalApp.device = res.data;
        //TODO:为编辑准备.
        deviceModalApp.title =deviceModalApp.device.name;
      }).catch(error => {
        VXETable.modal.message({content: `查找出错，原因是：${error.message}`, status: 'error'});
      })
    }

    /*TODO:提交 新增&编辑*/
    const onSubmit = (data) => {
      // debugger;
      //当为数组时用逗号连接
      if (data.eid) {
        //修改
        DeviceService.updateDevice(data).then((res) => {
          console.log(res);
          VXETable.modal.message({content: '操作成功', status: 'success'});
          setTimeout(onBack, 3000);
        }).catch(error => {
          VXETable.modal.message({content: `系统错误，原因是：${error.message}`, status: 'error'});
        })
      } else {
        //新增
        DeviceService.saveDevice(data).then((res) => {
          console.log(res);
          VXETable.modal.message({content: '操作成功', status: 'success'});
          saveFile(res.data.eid,"device",res.data);
          setTimeout(onBack, 3000);
        }).catch(error => {
          VXETable.modal.message({content: `系统错误，原因是：${error.message}`, status: 'error'});
        })
      }
    }

    /*TODO:继续提交*/
    const continueSubmit = () => {
      VXETable.modal.message({content: 'error 提示', status: 'error'});
    }

    /*TODO:返回列表*/
    const onBack = () => {
      router.push(`/repair/repairManagement/device`);
      store.dispatch('user/tabRemove', route.fullPath);
      setTimeout(() => {
        deviceGrid.value.commitProxy("query");
      }, 1500);
      deviceListApp.editModalShowing = false;
    }

    const saveFile = (associateFormId,associateFormName,data) => {
      if (imageRef.value.fileList.length !== 0) {
        let formData = new FormData();
        //表单名--对应实体表名
        let formDto = {associateFormId: associateFormId, associateFormName: associateFormName};
        let fileUploadDto = JSON.stringify(formDto)
        formData.append("fileUploadDto", new Blob([fileUploadDto], {type: "application/json"}));
        imageRef.value.fileList.forEach(file => {
          formData.append('files', file)
        });

        attachmentService.saveFile(formData).then((res) => {
          imageRef.value.fileList = [];
          console.log(res)
          VXETable.modal.message({content: '上传成功', status: 'success'});
          data.img=res.data.attachmentAddr
          DeviceService.updateDevice(data);
        }).catch((error) => {
          VXETable.modal.message({content: '上传失败' + `系统错误，原因是：${error.message}`, status: 'error'});
        });
      }

    }
    return {
      cityData,
      routeId,
      deviceListApp,
      deviceModalApp,
      onSubmit,
      continueSubmit,
      onBack,
      imageRef
    }

  },
})
</script>

<style scoped>

</style>
